#!/bin/bash

# 修复systemd服务配置和权限问题的脚本
set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否为root用户
check_root() {
    if [[ $EUID -ne 0 ]]; then
        log_error "请使用sudo运行此脚本"
        exit 1
    fi
}

# 修复目录和权限
fix_directories() {
    log_info "修复目录和权限..."
    
    # 创建必要的目录
    mkdir -p /opt/xiaozhi-server
    mkdir -p /tmp/xiaozhi-logs
    mkdir -p /var/log/xiaozhi-server
    
    # 创建xiaozhi用户（如果不存在）
    if ! id "xiaozhi" &>/dev/null; then
        log_info "创建xiaozhi用户..."
        useradd -r -s /bin/bash -d /opt/xiaozhi-server -c "XiaoZhi ESP32 Server" xiaozhi
    fi
    
    # 设置目录权限
    chown -R xiaozhi:xiaozhi /opt/xiaozhi-server
    chown -R xiaozhi:xiaozhi /tmp/xiaozhi-logs
    chown -R xiaozhi:xiaozhi /var/log/xiaozhi-server
    
    # 设置合适的权限
    chmod 755 /opt/xiaozhi-server
    chmod 755 /tmp/xiaozhi-logs
    chmod 755 /var/log/xiaozhi-server
    
    log_success "目录和权限修复完成"
}

# 创建简化的systemd服务文件
create_simple_service() {
    log_info "创建简化的systemd服务文件..."
    
    cat > /etc/systemd/system/xiaozhi-server.service << 'EOF'
[Unit]
Description=XiaoZhi ESP32 Server
After=network.target

[Service]
Type=simple
User=xiaozhi
Group=xiaozhi
WorkingDirectory=/opt/xiaozhi-server
ExecStart=/opt/xiaozhi-server/start_server.sh
Restart=on-failure
RestartSec=10
StartLimitInterval=60
StartLimitBurst=3

# 环境变量
Environment=PATH=/opt/miniconda3/envs/xiaozhi-server/bin:/usr/local/bin:/usr/bin:/bin
Environment=PYTHONUNBUFFERED=1
Environment=PYTHONIOENCODING=utf-8

# 日志配置
StandardOutput=append:/var/log/xiaozhi-server/server.log
StandardError=append:/var/log/xiaozhi-server/error.log
SyslogIdentifier=xiaozhi-server

[Install]
WantedBy=multi-user.target
EOF

    log_success "简化服务文件创建完成"
}

# 创建原始的完整服务文件（带安全策略）
create_full_service() {
    log_info "创建完整的systemd服务文件..."
    
    cat > /etc/systemd/system/xiaozhi-server.service << 'EOF'
[Unit]
Description=XiaoZhi ESP32 Server
Documentation=https://github.com/your-repo/xiaozhi-esp32-server
After=network.target network-online.target
Wants=network-online.target

[Service]
Type=simple
User=xiaozhi
Group=xiaozhi
WorkingDirectory=/opt/xiaozhi-server
ExecStart=/opt/xiaozhi-server/start_server.sh
ExecReload=/bin/kill -HUP $MAINPID
KillMode=mixed
KillSignal=SIGINT
TimeoutStopSec=30
Restart=on-failure
RestartSec=10
StartLimitInterval=60
StartLimitBurst=3

# 环境变量
Environment=PATH=/opt/miniconda3/envs/xiaozhi-server/bin:/usr/local/bin:/usr/bin:/bin
Environment=PYTHONUNBUFFERED=1
Environment=PYTHONIOENCODING=utf-8

# 日志配置
StandardOutput=append:/var/log/xiaozhi-server/server.log
StandardError=append:/var/log/xiaozhi-server/error.log
SyslogIdentifier=xiaozhi-server

# 资源限制
#LimitNOFILE=65536
#LimitNPROC=4096
#MemoryLimit=2G
#CPUQuota=200%

# 安全设置（简化版）
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/opt/xiaozhi-server /var/log/xiaozhi-server /tmp

[Install]
WantedBy=multi-user.target
EOF

    log_success "完整服务文件创建完成"
}

# 创建启动脚本
create_start_script() {
    log_info "创建启动脚本..."
    
    cat > /opt/xiaozhi-server/start_server.sh << 'EOF'
#!/bin/bash

# 小智ESP32服务器启动脚本
cd /opt/xiaozhi-server

# 检查conda环境
if [[ -f "/opt/miniconda3/etc/profile.d/conda.sh" ]]; then
    source /opt/miniconda3/etc/profile.d/conda.sh
    conda activate xiaozhi-server
else
    echo "警告: Conda环境未找到，使用系统Python"
fi

# 检查Python环境
if ! command -v python &> /dev/null; then
    echo "错误: Python未找到"
    exit 1
fi

# 启动服务
echo "启动小智ESP32服务器..."
exec python app.py
EOF

    chmod +x /opt/xiaozhi-server/start_server.sh
    chown xiaozhi:xiaozhi /opt/xiaozhi-server/start_server.sh
    
    log_success "启动脚本创建完成"
}

# 复制项目文件
copy_project_files() {
    log_info "复制项目文件..."
    
    # 获取当前脚本所在目录
    CURRENT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    
    if [[ -d "$CURRENT_DIR" ]]; then
        log_info "从 $CURRENT_DIR 复制文件到 /opt/xiaozhi-server"
        
        # 复制项目文件
        cp -r "$CURRENT_DIR"/* /opt/xiaozhi-server/
        
        # 设置权限
        chown -R xiaozhi:xiaozhi /opt/xiaozhi-server
        
        log_success "项目文件复制完成"
    else
        log_error "当前目录不存在: $CURRENT_DIR"
        exit 1
    fi
}

# 重新加载systemd配置
reload_systemd() {
    log_info "重新加载systemd配置..."
    systemctl daemon-reload
    log_success "systemd配置已重新加载"
}

# 测试服务
test_service() {
    log_info "测试服务启动..."
    
    # 停止服务（如果正在运行）
    systemctl stop xiaozhi-server 2>/dev/null || true
    
    # 启动服务
    if systemctl start xiaozhi-server; then
        sleep 5
        if systemctl is-active --quiet xiaozhi-server; then
            log_success "服务启动成功！"
            return 0
        else
            log_error "服务启动失败"
            return 1
        fi
    else
        log_error "服务启动失败"
        return 1
    fi
}

# 显示状态
show_status() {
    log_info "服务状态："
    echo "========================================"
    systemctl status xiaozhi-server --no-pager -l
    echo "========================================"
    
    log_info "xiaozhi用户信息："
    id xiaozhi
    echo "========================================"
    
    log_info "目录权限："
    ls -la /opt/xiaozhi-server/
    echo "========================================"
    
    log_info "日志目录："
    ls -la /var/log/xiaozhi-server/
    echo "========================================"
}

# 显示日志
show_logs() {
    log_info "最近的错误日志："
    if [[ -f "/var/log/xiaozhi-server/error.log" ]]; then
        tail -n 50 /var/log/xiaozhi-server/error.log
    else
        log_warning "错误日志文件不存在"
    fi
    
    echo "========================================"
    log_info "最近的服务日志："
    journalctl -u xiaozhi-server -n 50 --no-pager
}

# 主函数
main() {
    local mode=${1:-simple}
    
    check_root
    
    log_info "开始修复systemd服务配置..."
    log_info "模式: $mode"
    
    fix_directories
    copy_project_files
    create_start_script
    
    case "$mode" in
        simple)
            create_simple_service
            ;;
        full)
            create_full_service
            ;;
        *)
            log_error "未知模式: $mode"
            log_info "支持的模式: simple, full"
            exit 1
            ;;
    esac
    
    reload_systemd
    
    if test_service; then
        show_status
        log_success "修复完成！服务已成功启动"
        log_info "您可以使用以下命令管理服务器："
        log_info "  sudo systemctl status xiaozhi-server  # 查看状态"
        log_info "  sudo systemctl stop xiaozhi-server    # 停止服务"
        log_info "  sudo systemctl restart xiaozhi-server # 重启服务"
        log_info "  sudo ./manage_service.sh logs service 100  # 查看日志"
    else
        log_error "修复失败，正在显示诊断信息..."
        show_logs
        log_info "请检查以上日志信息，或尝试使用简单模式："
        log_info "  sudo ./fix_systemd.sh simple"
        exit 1
    fi
}

# 运行主函数
main "$@"